package com.suning.sawp.service.impl.mainpushnew;

import java.math.BigDecimal;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.suning.sawp.constants.ErrorCodeConstants;
import com.suning.sawp.dto.common.ReturnMsg;
import com.suning.sawp.dto.mainpush.StoreManDto;
import com.suning.sawp.intf.dao.mainpushnew.MainPushQueryDao;
import com.suning.sawp.intf.mainpushnew.MainPushQueryService;
import com.suning.sawp.intf.storeman.StoreManService;
import com.suning.sawp.service.util.DateUtils;
import com.suning.sawp.vo.mainpushnew.MainPushModelVo;
import com.suning.sawp.vo.mainpushnew.MainPushStaffModelVo;
import com.suning.sawp.vo.mainpushnew.MainPushStaffVo;
import com.suning.sawp.vo.mainpushnew.MainPushStaffidDetailVo;
import com.suning.sawp.vo.mainpushnew.MainPushStaffidVo;
import com.suning.sawp.vo.mainpushnew.MainPushStoreVo;

/**
 * 主推任务查询
 * 
 * @author 15050769
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
@Service
public class MainPushQueryServiceImpl implements MainPushQueryService {

    @Resource
    MainPushQueryDao mainPushQueryDao;

    @Resource
    StoreManService storeManService;

    private static final Logger LOGGER = LoggerFactory.getLogger(MainPushQueryServiceImpl.class);

    private static String QUERY_MONTH = "0";

    private static String QUERY_DAY = "1";

    @Override
    public ReturnMsg<MainPushStoreVo> queryMainPushForStore(String cateCode, String month, String storeCode) {
        LOGGER.info("queryMainPushForStore ,cateCode:{},month:{},storeCode:{}", cateCode, month, storeCode);
        ReturnMsg<MainPushStoreVo> resultMsg = new ReturnMsg<MainPushStoreVo>();

        try {

            if (StringUtils.isBlank(month)) {
                month = DateUtils.getThisMonth();
            }
            List<MainPushModelVo> modelList = mainPushQueryDao.queryMainPushModelListForStore(cateCode, month,
                    storeCode);

            MainPushStoreVo mainPushStoreVo = new MainPushStoreVo();
            for (MainPushModelVo item : modelList) {

                if (item != null) {
                    mainPushStoreVo.setStoreTaskId(item.getStoreTaskId());
                }
                if (item == null || item.getCompleteNum() == null || item.getDistNum() == null
                        || item.getDistNum().equals(new BigDecimal(0))) {
                    continue;
                }
                item.setCompleteRate(item.getCompleteNum().divide(item.getDistNum(), 3, BigDecimal.ROUND_HALF_UP));
            }

            mainPushStoreVo.setMonth(DateUtils.getThisMonth());
            // 查询总销售额
            BigDecimal totalAmount = mainPushQueryDao.queryStoreAmount(cateCode, month, storeCode);
            if (totalAmount != null) {
                mainPushStoreVo.setTotalAmount(totalAmount.setScale(2, BigDecimal.ROUND_HALF_UP));
            }

            // 查询主推销售额
            BigDecimal mainPushAmount = mainPushQueryDao.queryMainPushStoreAmount(cateCode, month, storeCode);
            if (mainPushAmount != null) {
                mainPushStoreVo.setSalesAmount(mainPushAmount.setScale(2, BigDecimal.ROUND_HALF_UP));
            }

            // 主推销售额占比
            if (totalAmount != null && mainPushAmount != null) {
                mainPushStoreVo.setCompleteRate(mainPushAmount.divide(totalAmount, 3, BigDecimal.ROUND_HALF_UP));
            }
            mainPushStoreVo.setMainPushModelVoList(modelList);
            LOGGER.info("queryMainPushForStore ,mainPushStoreVo:{}", mainPushStoreVo);
            resultMsg.setData(mainPushStoreVo);
        } catch (Exception e) {
            resultMsg.setError(ErrorCodeConstants.ERR_0002);
            LOGGER.error("queryMainPushForStore Exception", e);
        }
        return resultMsg;
    }

    @Override
    public ReturnMsg<MainPushStaffidVo> queryMainPushDetailForStore(String modelId, String queryParm, String queryType,
            StoreManDto storeManDto, String storeTaskId) {
        LOGGER.info("queryMainPushDetailForStore ,modelId:{},queryParm:{},queryType:{}", modelId, queryParm, queryType);
        ReturnMsg<MainPushStaffidVo> resultMsg = new ReturnMsg<MainPushStaffidVo>();
        try {
            // 默认本月
            if (QUERY_MONTH.equals(queryType)) {
                if (StringUtils.isBlank(queryParm)) {
                    queryParm = DateUtils.getThisMonth();
                }
                MainPushStaffidVo result = queryMainPushDetailByMonth(modelId, queryParm, storeManDto.getStoreCode(),
                        storeTaskId);
                result.setCurrentDate(DateUtils.getThisMonth());
                resultMsg.setData(result);
            } else if (QUERY_DAY.equals(queryType)) {
                // 默认昨天
                if (StringUtils.isBlank(queryParm)) {
                    queryParm = DateUtils.getNextDayStr(-1, DateUtils.YYYYMMDD_PATTERN);
                }
                MainPushStaffidVo result = queryMainPushDetailByDay(modelId, queryParm, storeManDto.getStoreCode(),
                        storeTaskId);
                result.setCurrentDate(DateUtils.getNextDayStr(-1, DateUtils.YYYYMMDD_PATTERN));
                resultMsg.setData(result);
            } else {
                resultMsg.setError(ErrorCodeConstants.ERR_0001);
                return resultMsg;
            }
        } catch (Exception e) {
            LOGGER.error("queryMainPushDetailForStore exception ", e);
            resultMsg.setError(ErrorCodeConstants.ERR_0002);
        }
        return resultMsg;
    }

    private MainPushStaffidVo queryMainPushDetailByMonth(String modelId, String queryParm, String storeCode,
            String storeTaskId) {
        List<MainPushStaffidDetailVo> queryList = mainPushQueryDao.queryMainPushDetailByMonth(modelId, queryParm,
                storeCode, storeTaskId);
        improveQueryList(queryList);
        MainPushStaffidVo mainPushStaffidVo = new MainPushStaffidVo();
        mainPushStaffidVo.setTotalNum(improveQueryList(queryList));
        mainPushStaffidVo.setStaffList(queryList);
        if (DateUtils.getNextDayStr(-1, DateUtils.YYYYMM_PATTERN).equals(queryParm)) {
            mainPushStaffidVo.setEndTime(queryParm);
        } else {
            mainPushStaffidVo.setEndTime(DateUtils.getLastDateOfMonthStr(
                    DateUtils.getDateByStr(queryParm, DateUtils.YYYYMM_PATTERN), DateUtils.YYYYMMDD_PATTERN));
        }
        return mainPushStaffidVo;
    }

    private MainPushStaffidVo queryMainPushDetailByDay(String modelId, String queryParm, String storeCode,
            String storeTaskId) {
        List<MainPushStaffidDetailVo> queryList = mainPushQueryDao.queryMainPushDetailByDay(modelId, queryParm,
                storeCode, storeTaskId);
        MainPushStaffidVo mainPushStaffidVo = new MainPushStaffidVo();
        mainPushStaffidVo.setTotalNum(improveQueryList(queryList));
        mainPushStaffidVo.setStaffList(queryList);
        return mainPushStaffidVo;
    }

    private BigDecimal improveQueryList(List<MainPushStaffidDetailVo> queryList) {
        BigDecimal count = new BigDecimal(0);
        if (CollectionUtils.isNotEmpty(queryList)) {
            for (MainPushStaffidDetailVo item : queryList) {
                if (item != null && StringUtils.isNotBlank(item.getStaffId())
                        && StringUtils.isBlank(item.getStaffName())) {
                    try {
                        StoreManDto storeManDto = storeManService.queryStoreManAttachInfo(item.getStaffId());
                        item.setStaffName(storeManDto.getStaffName());
                    } catch (Exception e) {
                        LOGGER.error("improveQueryList exception ", e);
                    }
                }
                if (item != null &&item.getMainPushNum() != null) {
                    count = count.add(item.getMainPushNum());
                }
                if (item == null || item.getMainPushNum() == null || item.getTotalNum() == null
                        || item.getTotalNum().equals(new BigDecimal(0))) {
                    continue;
                }
                item.setMainPushRate(item.getMainPushNum().divide(item.getTotalNum(), 3, BigDecimal.ROUND_HALF_UP));
            }
        }
        return count;
    }

    @Override
    public ReturnMsg<MainPushStaffVo> queryMainPushForStaff(String cateCode, String month, StoreManDto storeManDto) {

        LOGGER.info("queryMainPushForStaff ,cateCode:{},month:{},staffid:{}", cateCode, month, storeManDto.getStaffId());
        ReturnMsg<MainPushStaffVo> resultMsg = new ReturnMsg<MainPushStaffVo>();

        try {
            if (StringUtils.isBlank(month)) {
                month = DateUtils.getThisMonth();
            }
            List<MainPushStaffModelVo> modelList = mainPushQueryDao.queryMainPushForStaff(cateCode, month,
                    storeManDto.getStoreCode(), storeManDto.getStaffId());
            BigDecimal compleleNum = new BigDecimal(0);
            BigDecimal totalNum = new BigDecimal(0);

            for (MainPushStaffModelVo item : modelList) {
                if (item != null) {
                    if (item.getCompleteNum() != null) {
                        compleleNum = compleleNum.add(item.getCompleteNum());
                    }

                    if (item.getTargetNum() != null) {
                        totalNum = totalNum.add(item.getTargetNum());
                    }
                }
            }

            MainPushStaffVo mainPushStaffVo = new MainPushStaffVo();
            if (!totalNum.equals(new BigDecimal(0))) {
                mainPushStaffVo.setCompleteRate(compleleNum.divide(totalNum, 3, BigDecimal.ROUND_HALF_UP));
            }
            mainPushStaffVo.setMainPushModelVoList(modelList);
            mainPushStaffVo.setMonth(DateUtils.getThisMonth());
            LOGGER.info("queryMainPushForStaff ,mainPushStaffVo:{}", mainPushStaffVo);
            resultMsg.setData(mainPushStaffVo);
        } catch (Exception e) {
            resultMsg.setError(ErrorCodeConstants.ERR_0002);
            LOGGER.error("queryMainPushForStaff Exception", e);
        }
        return resultMsg;

    }
}
